<template>
  <div
    class="customer-list-container"
    ref="customerListPage"
    v-loading.fullscreen.lock="loadingListData"

  >
    <!--搜索-->
    <div ref="tableHeaderContainer" class="customer-list-search-group-container  list-search-group-container">

      <div class="list-header-seach">
        <!-- 视图列表 -->
        <viewport-dropdown
          ref="viewportListRef"
          module="customer"
          :current-view="currentView"
          @choose="chooseView"
          @edit="editViewByViewport"
          @create="editViewByViewport"
          :pre-views="preViews"></viewport-dropdown>
        <!-- 视图编辑弹框 -->
        <advanced-search-modal
          ref="advancedSearchModalRef"
          module="customer"
          :fields="searchFieldInfo"
          @save="handleViewportSave">
          <!-- <div class="task-common-advanced-search-form" slot="prefix">
            <div class="search-row">
              <div class="search-row__label">快捷条件：</div>
              <div class="search-row__content">
                <el-tag class="__tag" type="info"> 创建视角：{{visualAngle}} </el-tag>
              </div>
            </div>
          </div> -->
        </advanced-search-modal>

        <form class="base-search" onsubmit="return false;">
          <!--              :placeholder="$t('customer.searchPlaceholder')"-->
          <div class="task-flex">
            <el-input
              v-model="params.keyword"
              v-trim:blur
              :placeholder=" params.searchCondition === '' ? $t('customer.searchPlaceholder') : t('task.model.tip.searchTaskTip3') "
              class="task-select-search-input input-with-append-search task-mr12">
              <!--              <i slot="prefix" class="el-input__icon el-icon-search"></i>-->
              <el-select
                v-model="params.searchCondition"
                placeholder="$t('common.placeholder.select')"
                slot="prepend"
                class="task-with-select"
              >
                <el-option :label="$t('task.list.formContent')" value=""></el-option>
                <el-option :label="$t('task.record.taskCard')" value="ADDITIONAL"></el-option>
              </el-select>

              <el-button
                type="primary"
                slot="append"
                @click="params.pageNum=1;search();trackEventHandler('search')"
                native-type="submit"
                v-track="$track.formatParams('KEYWORD_SEARCH')"
              >{{$t('common.base.search')}}</el-button>
            </el-input>
            <el-button type="plain-third" @click="resetParams" v-track="$track.formatParams('RESET_SEARCH')">{{$t('common.base.reset')}}</el-button>
          </div>
          <!-- <span class="advanced-search-visible-btn" @click.self="panelSearchAdvancedToggle">
            <i class="iconfont icon-filter"></i>
            高级搜索
          </span> -->
          <span class="advanced-search-visible-btn">
            <advanced-search
              :fields="searchFieldInfo"
              :search-model="viewportSearchModel"
              :in-common-use="inCommonUse"
              :has-save="!!(currentView && currentView.viewId && currentView.authEdit)"
              module="customer"
              @changeCommonUse="changeCommonUse"
              @search="handleAdvancedSearch"
              @create="createViewBySearchModel"
              @save="updateViewBySearchModel"
            />
          </span>
        </form>
      </div>
    </div>

    <!--list start-->
    <div class="customer-list-component" :class="customerListClassNames">
      <!--operation bar start-->
      <div ref="tableDoContainer" class="operation-bar-container task-ai">
        <div class="top-btn-group task-flex task-ai">
          <el-button
            type="primary"
            @click="jumpPage"
            v-if="createdPermission"
            v-track="$track.formatParams('TO_CREATE')">
            {{$t('common.base.create')}}
          </el-button>

          <!-- 智能计划 -->
          <el-button
            type="plain-third"
            @click="handleCommand('smartPlan')"
            v-if="isShowCreateSmartPlan"
          >
            {{ $t('smartPlan.title') }}
          </el-button>

          <!-- 触发器 -->
          <!-- TODO: 暂不显示 -->
          <!-- <el-button
            v-for="item in triggerButtonList"
            :key="item.id"
            type="plain-third"
            @click="handleCommand(item)"
          >
            {{ item.triggerName }}
          </el-button> -->

          <!-- start 发送短信 -->
          <el-button type="plain-third" @click="openDialog('sendMessage')" v-if="isShowSendSMS" v-track="$track.formatParams('SEND_MESSAGE')">
            {{$t('common.base.sendSMS')}}
          </el-button>

          <el-button
            type="plain-third"
            @click="openDialog('sendEmail')"
            v-if="isShowEmail"
            v-track="$track.formatParams('SEND_EMAIL')">
            {{$t('common.base.sendEmail')}}
          </el-button>
          <!-- end 发送邮件 -->

          <!-- 发送活动调研 -->
          <send-activity-research v-if="isShowSendActivity" mode="CUSTOMER" :selection="multipleSelection"></send-activity-research>

          <el-button
            type="plain-third"
            @click="openDialog('remind')"
            v-if="editedPermission === 3 && isShowCustomerRemind"
            v-track="$track.formatParams('BATCH_REMIND')">
            {{$t('common.base.batchRemind')}}
          </el-button>
          <!-- end 批量提醒 -->

          <el-button
            type="plain-third"
            @click="openDialog('edit')"
            v-if="editedPermission === 3"
            v-track="$track.formatParams('BATCH_EDIT')">
            {{$t('common.base.bulkEdit')}}
          </el-button>

          <el-button
            type="plain-third"
            @click="deleteCustomer"
            v-if="deletePermission"
            v-track="$track.formatParams('DELETE')">
            {{$t('common.base.batchDelete')}}
          </el-button>

          <!-- 批量操作（除新建以外的其它按钮） -->
          <el-dropdown
            v-if="isShowBatchOperation"
            :hide-on-click="false"
            trigger="click"
            @command="handleCommand"
          >
            <el-button type="plain-third">{{ $t('part.text40') }}</el-button>
            <el-dropdown-menu class="batch-operation-dropdown-menu" slot="dropdown">
              <!-- 新建智能计划 -->
              <el-dropdown-item v-if="isShowCreateSmartPlan" command="smartPlan">
                <div class="dropdown-name">{{ $t('smartPlan.title') }}</div>
                <div
                  class="dropdown-iconfont flex-x"
                  @click.stop="tileButton(buttonStorageModule, buttonStorageKey, 'smartPlan', {tile: smartPlanButtonTile})"
                >
                  <i class="iconfont" :class="[smartPlanButtonTile ? 'icon-pushpin-fill' : 'icon-pushpin']"></i>
                </div>
              </el-dropdown-item>
              <!-- 触发器 -->
              <el-dropdown-item v-for="item in triggerList" :key="item.id" :command="item">
                <div class="dropdown-name">{{ item.triggerName }}</div>
                <div
                  class="dropdown-iconfont flex-x"
                  @click.stop="tileButton(buttonStorageModule, buttonStorageKey, item.id, {tile: getButtonTile(item.id)})"
                >
                  <i class="iconfont" :class="[getButtonTile(item.id) ? 'icon-pushpin-fill' : 'icon-pushpin']"></i>
                </div>
              </el-dropdown-item>
              <!-- 发送短信 -->
              <el-dropdown-item v-if="isShowSendSMS" command="sendMessage">
                <div class="dropdown-name">{{ $t('common.base.sendSMS') }}</div>
                <div
                  class="dropdown-iconfont flex-x"
                  @click.stop="tileButton(buttonStorageModule, buttonStorageKey, 'sendMessage', {tile: sendMessageButtonTile})"
                >
                  <i class="iconfont" :class="[sendMessageButtonTile ? 'icon-pushpin-fill' : 'icon-pushpin']"></i>
                </div>
              </el-dropdown-item>
              <!-- 发送邮件 -->
              <el-dropdown-item v-if="isShowEmail" command="sendEmail">
                <div class="dropdown-name">{{ $t('common.base.sendEmail') }}</div>
                <div
                  class="dropdown-iconfont flex-x"
                  @click.stop="tileButton(buttonStorageModule, buttonStorageKey, 'sendEmail', {tile: sendEmailButtonTile})"
                >
                  <i class="iconfont" :class="[sendEmailButtonTile ? 'icon-pushpin-fill' : 'icon-pushpin']"></i>
                </div>
              </el-dropdown-item>
              <!-- 发送活动调研 -->
              <el-dropdown-item v-if="isShowSendActivity" command="sendActivity">
                <div class="dropdown-name">
                  <send-activity-research ref="sendActivityResearch" mode="CUSTOMER" :selection="multipleSelection">
                    {{ $t('customer.sendActivitySurvey') }}
                  </send-activity-research>
                </div>
                <div
                  class="dropdown-iconfont flex-x"
                  @click.stop="tileButton(buttonStorageModule, buttonStorageKey, 'sendActivity', {tile: sendActivityButtonTile})"
                >
                  <i class="iconfont" :class="[sendActivityButtonTile ? 'icon-pushpin-fill' : 'icon-pushpin']"></i>
                </div>
              </el-dropdown-item>
              <!-- 批量提醒 -->
              <el-dropdown-item v-if="editedPermission === 3 && isShowCustomerRemind" command="remind">
                <div class="dropdown-name">{{ $t('common.base.batchRemind') }}</div>
                <div
                  class="dropdown-iconfont flex-x"
                  @click.stop="tileButton(buttonStorageModule, buttonStorageKey, 'remind', {tile: remindButtonTile})"
                >
                  <i class="iconfont" :class="[remindButtonTile ? 'icon-pushpin-fill' : 'icon-pushpin']"></i>
                </div>
              </el-dropdown-item>
              <!-- 批量编辑 -->
              <el-dropdown-item v-if="editedPermission === 3" command="edit">
                <div class="dropdown-name">{{ $t('common.base.bulkEdit') }}</div>
                <div
                  class="dropdown-iconfont flex-x"
                  @click.stop="tileButton(buttonStorageModule, buttonStorageKey, 'edit', {tile: editButtonTile})"
                >
                  <i class="iconfont" :class="[editButtonTile ? 'icon-pushpin-fill' : 'icon-pushpin']"></i>
                </div>
              </el-dropdown-item>
              <!-- 删除 -->
              <el-dropdown-item v-if="deletePermission" command="delete">
                <div class="dropdown-name">{{ $t('common.base.batchDelete') }}</div>
                <div
                  class="dropdown-iconfont flex-x"
                  @click.stop="tileButton(buttonStorageModule, buttonStorageKey, 'delete', {tile: deleteButtonTile})"
                >
                  <i class="iconfont" :class="[deleteButtonTile ? 'icon-pushpin-fill' : 'icon-pushpin']"></i>
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <template v-if="pageButtonSetGray">
            <template v-for="(item, index) in pageButtonList">
              <el-button
                :type="item.viewType"
                @click="handlePageButtonClick(item)"
                :loading="[ButtonSetDetailForButtonConcatEventEnum.Trigger, ButtonSetDetailForButtonConcatEventEnum.Code].includes(item.event[0] && item.event[0].type) && pageButtonLoading"
                >
                {{item.name}}
              </el-button>
            </template>
          </template>
        </div>

        <div class="action-button-group">
          <!-- start 客户标签筛选 -->
          <biz-customer-tag-select v-if="_isShowCustomerTag" @change="searchCustomerTags" />
          <!-- end 客户标签筛选 -->

          <el-dropdown trigger="click" v-if="exportPermission">
            <span class="el-dropdown-link cur-point" @click="trackEventHandler('moreAction')">
              {{$t('common.base.moreOperator')}}
              <i class="iconfont icon-fdn-select"></i>
            </span>
            <el-dropdown-menu slot="dropdown">

              <el-dropdown-item v-if="!isExperienceEdition && isButtonDisplayed && canCustomerImport && createdPermission">
                <div @click="openDialog('importCustomer')" v-track="$track.formatParams('IMPORT_CUSTOMER', null, 'MORE_ACTIONS')">{{$t('common.base.importCustomer')}}</div>
              </el-dropdown-item>

              <el-dropdown-item v-if="!isExperienceEdition && isButtonDisplayed && canCustomerImport">
                <div @click="openDialog('importLinkman')" v-track="$track.formatParams('IMPORT_LINKMAN', null, 'MORE_ACTIONS')">{{$t('common.base.importContact')}}</div>
              </el-dropdown-item>

              <el-dropdown-item v-if="isButtonDisplayed && canCustomerExport">
                <div @click="exportCustomer(false)" v-track="$track.formatParams('EXPORT', null, 'MORE_ACTIONS')">{{$t('common.base.export')}}</div>
              </el-dropdown-item>

              <el-dropdown-item v-if="isButtonDisplayed && canCustomerExport">
                <div @click="exportCustomer(true)" v-track="$track.formatParams('EXPORT_ALL', null, 'MORE_ACTIONS')">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>

              <el-dropdown-item v-if="editedPermission || createdPermission">
                <div @click="mergeCustomer" v-track="$track.formatParams('MERGE_CUSTOMER', null, 'MORE_ACTIONS')">{{$t('customer.mergeCustomer.mergeCustomerBtn')}}</div>
              </el-dropdown-item>

              <el-dropdown-item v-if="!isExperienceEdition && canCustomerImport">
                <div @click="openDialog('update')" v-track="$track.formatParams('BATCH_UPDATE', null, 'MORE_ACTIONS')">{{$t('common.base.batchUpdate')}}</div>
              </el-dropdown-item>

              <!-- start 批量添加标签 -->
              <el-dropdown-item v-if="_isShowCustomerTag">
                <div @click="handleClickAddTag" v-track="$track.formatParams('BATCH_ADD_TAG', null, 'MORE_ACTIONS')">{{$t('customer.batchAddTag')}}</div>
              </el-dropdown-item>
              <!-- end 批量添加标签 -->

            </el-dropdown-menu>
          </el-dropdown>
          <span class="el-dropdown-link cur-point" @click="showAdvancedSetting" v-track="$track.formatParams('SELECT_COLUMN')">
            {{$t('common.base.choiceCol')}}
            <i class="iconfont icon-fdn-select"></i>
          </span>
        </div>
      </div>
      <!--operation bar end-->

      <div class="pad-l-16 pad-r-16 bg-w">
        <el-table
          :data="customers"
          stripe
          border
          @select="handleSelection"
          @select-all="handleSelection"
          @sort-change="sortChange"
          @header-dragend="headerDragend"
          :row-key="getRowKey"
          :highlight-current-row="false"
          header-row-class-name="customer-table-header"
          ref="multipleTable"
          :key="tableKey"
          :class="['customer-table', 'common-list-table', 'bg-w', 'bbx-normal-list-box']"
          :height="tableContainerHeight"
        >
          <template slot="empty">
            <BaseListForNoData v-show="!loadingListData" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
          </template>
          <el-table-column
            type="selection"
            width="48"
            align="center"
            class-name="select-column"></el-table-column>
          <el-table-column
            v-for="(column, index) in columns.filter(item => item.show)"
            :key="`${column.field}_${tableKey}_${index}`"
            :label="column.label"
            :prop="column.field"
            :width="column.width"
            :min-width="column.minWidth || '120px'"
            :class-name="column.field == 'name' ? 'customer-name-superscript-td' : ''"
            :sortable="column.sortable"
            :show-overflow-tooltip="column.field === 'name' || column.field !== 'customerTag'"
            :align="column.align"
            :fixed="column.fixLeft || false"
          >
            <template slot-scope="scope">
              <template v-if="column.field === 'name'">
                <sample-tooltip :row="scope.row">
                  <template slot="content" slot-scope="{isContentTooltip}">
                    <el-tooltip
                      :content="scope.row[column.field]"
                      placement="top"
                      :disabled="!isContentTooltip"
                    >
                      <div class="customer-name-block">
                        <div
                          href
                          :class="[
                            scope.row.isGuideData ? column.className : scope.row.hasWechat || scope.row.canChat ? 'customer-name-wx' : '',
                            globalIsHaveCustomerViewDetailAuth ? 'view-detail-btn' : 'view-detail-btn-disabled'
                          ]"
                          class="view-detail-btn"
                          @click.stop.prevent="createCustomerTab(scope.row.id)">
                          <pre class="pre-text no-base-tip">{{ scope.row[column.field] }}</pre>
                        </div>
                        <biz-wx-chat-button :customer-id="scope.row.id" @click="wxchatButtonClickHandler(scope.row.id)" v-if="scope.row.canChat"/>
                        <ui-wx-tag v-else-if="scope.row.hasWechat" />
                      </div>
                    </el-tooltip>
                  </template>
                </sample-tooltip>
              </template>
              <template v-else-if="column.formType === 'connector'">
                <div v-if="scope.row.attribute && scope.row.attribute[column.field]" class="view-detail-btn task-client" @click.stop="openConnectorDialog(column, scope.row)">
                  {{$t('common.base.view')}}
                </div>
              </template>
              <template v-else-if="column.field === 'customerAddress'">
                {{formatAddress(scope.row[column.field])}}
              </template>
              <template v-else-if="column.field === 'detailAddress'">
                <pre class="pre-text">{{scope.row.customerAddress && scope.row.customerAddress.adAddress}}</pre>
              </template>
              <template v-else-if="column.field === 'tags' && scope.row.tags">
                {{scope.row.tags | tagName}}
              </template>
              <template v-else-if="column.field === 'status'">
                <el-switch
                  :disabled="scope.row.pending || tableStatusIsOpen"
                  @change="toggleStatus(scope.row)"
                  :value="Boolean(scope.row.status)"
                ></el-switch>
              </template>
              <template v-else-if="column.field === 'updateTime'">
                <template v-if="scope.row.latesetUpdateRecord && !isOpenData">
                  <el-tooltip
                    :content="scope.row.latesetUpdateRecord"
                    class="item"
                    effect="dark"
                    placement="top"
                  >
                    <div @mouseover="showLatestUpdateRecord(scope.row)">{{$formatFormField(column, scope.row)}}</div>
                  </el-tooltip>
                </template>
                <template v-else>
                  <div @mouseover="showLatestUpdateRecord(scope.row)">{{$formatFormField(column, scope.row)}}</div>
                </template>
              </template>
              <template v-else-if="column.field === 'lmPhone'">
                <span class="align-items-center"> {{scope.row.lmPhone}}
                  <biz-call-icon :value="scope.row.lmPhone" :sourceData="callCenterSourceData(scope)" />
                </span>
              </template>
              <template v-else-if="column.field === 'createUser'">
                <template v-if="isOpenData">
                  <open-data type='userName' :openid="scope.row.createUserStaffId"></open-data>
                </template>
                <template v-else>
                  {{scope.row.createUserName}}
                </template>
              </template>
              <template v-else-if="column.field === 'customerManagerName'">
                <template v-if="isOpenData">
                  <open-data type='userName' :openid="scope.row.customerManagerStaffId"></open-data>
                </template>
                <template v-else>
                  {{scope.row.customerManagerName}}
                </template>
              </template>
              <template v-else-if="column.field === 'remindCount'">
                {{scope.row.attribute && scope.row.attribute.remindCount || 0}}
              </template>
              <template v-else-if="column.formType === 'location'">
                {{ scope.row.attribute[column.field] && scope.row.attribute[column.field].address}}
              </template>
              <template v-else-if="column.formType === 'address'">
                {{formatCustomizeAddress(scope.row.attribute[column.field])}}
              </template>

              <div
                class="pre-text"
                v-else-if="column.formType === 'textarea'"
                v-html="buildTextarea(scope.row.attribute[column.field])"
                @click="openOutsideLink"></div>

              <template v-else-if="column.formType === 'user'">

                <template v-if="isOpenData">
                  <template v-if="Array.isArray(scope.row.attribute[column.field] || scope.row[column.field])">
                    <open-data
                      v-for="item in (scope.row.attribute[column.field] || scope.row[column.field])"
                      :key="item.staffId"
                      type="userName"
                      :openid="item.staffId"></open-data>
                  </template>
                  <template v-else>
                    <open-data type="userName" :openid="scope.row.attribute[column.field] && scope.row.attribute[column.field].staffId"></open-data>
                  </template>
                </template>

                <template v-else>
                  <pre class="pre-text">{{ $formatFormField(column, scope.row) }}</pre>
                </template>

              </template>

              <template v-else-if="column.formType === 'related_customers'">
                <div>
                  <span v-for="(customer, index) in scope.row.attribute[column.field] || ['']">
                    <span v-if="customer && index !== 0">、</span>
                    <span v-if="customer" class="link" @click="createCustomerTab(customer.id, `&sourceCustomerId=${scope.row.id}&fieldName=${column.field}`)">
                      {{ customer.name }}
                    </span>
                  </span>
                </div>
              </template>
              <!-- 富文本 -->
              <template v-else-if="column.formType === 'richtext'">
                <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
                  <span v-if="scope.row.attribute && scope.row.attribute[column.field]">{{$t('common.base.view')}}</span>
                </div>
              </template>

              <template v-else-if="column.isSystem === 0">
                <pre class="pre-text">{{ $formatFormField(column, scope.row) }}</pre>
              </template>
              <template v-else-if="column.field === 'customerTag'">
                <el-tooltip placement="top" v-if="customerTagShow">
                  <div slot="content">
                    {{  scope.row.tenantTagList | tagName }}
                  </div>
                  <base-tags :value="customerLabel(scope.row.tenantTagList)" />
                </el-tooltip>
              </template>
              <template v-else-if="column.field === 'parentCustomer'">
                <div v-if="scope.row.parentCustomer" class="view-detail-btn" @click="createCustomerTab(scope.row.parentCustomer.customerId, null, true)">
                  {{ scope.row.parentCustomer.customerName || '' }}
                </div>
              </template>

              <!-- <template v-else-if="column.field === 'synergies'">
                {{scope.row[column.field] | fmt_form_user}}
              </template> -->

              <template v-else>
                <pre class="pre-text">{{ $formatFormField(column, scope.row) }}</pre>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer-10">
        <div class="list-info">
          <i18n path="common.base.table.totalCount">
            <span place="count" class="level-padding">{{totalItems}}</span>
          </i18n>
          <template v-if="multipleSelection&&multipleSelection.length>0">
            <i18n path="common.base.table.selectedNth">
              <span
                place="count"
                class="customer-selected-count"
                @click="multipleSelectionPanelShow = true"
              >{{multipleSelection.length}}</span>
            </i18n>
            <span class="customer-selected-count" @click="toggleSelection()">{{$t('common.base.clear')}}</span>
          </template>
        </div>
        <el-pagination
          class="customer-table-pagination"
          background
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="params.pageSize"
          :current-page="params.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="totalItems"
        ></el-pagination>
      </div>
    </div>
    <!--list end-->

    <!-- dialog of operation -->
    <batch-reminding-customer-dialog
      ref="batchRemindingCustomerDialog"
      modal="customer"
      :selected-ids="selectedIds"
      @success-callback="remindSuccess"
    ></batch-reminding-customer-dialog>

    <biz-send-message
      ref="messageDialog"
      :type="'repeatPhone'"
      :selected-ids="selectedIds"
      :sms-rest="smsRest"></biz-send-message>

    <biz-send-email ref="emailDialog" :selected-ids="selectedIds" mode="CUSTOMER"></biz-send-email>

    <batch-editing-customer-dialog
      ref="batchEditingCustomerDialog"
      :config="{fields: fieldInfo, defaultAddress: defaultAddress}"
      :callback="search"
      :selected-ids="selectedIds"
      :select-list="multipleSelection"
      :initData="initData"
    ></batch-editing-customer-dialog>

    <!-- start 批量更新 -->
    <batch-update-customer-dialog
      ref="batchUpdateCustomerDialog"
      :selected-ids="selectedIds"
      :total-items="totalItems"
      :build-download-params="buildParams"
      action="/excels/customer/update"
    ></batch-update-customer-dialog>
    <!-- end 批量更新 -->

    <!-- start 导入客户 -->
    <base-import :title="$t('common.base.importCustomer')" ref="importCustomerModal" :action="customerListImport_1">
      <div slot="tip">
        <div class="base-import-warn">
          <i18n path="common.base.importModal.downloadTemplateTip">
            <a :href="customerListImportTem_1" place="link">{{$t('common.base.importModal.importTemplate')}}</a>
          </i18n>
        </div>
      </div>
    </base-import>
    <!-- end 导入客户 -->

    <!-- start 导入联系人 -->
    <base-import
      :title="$t('common.base.importContact')"
      ref="importLinkmanModal"
      @success="importSucc"
      :action="customerListImport_2"
    >
      <div slot="tip">
        <div class="base-import-warn">
          <i18n path="common.base.importModal.downloadTemplateTip" tag="p" style="margin: 0">
            <a :href="customerListImportTem_2" place="link">{{$t('common.base.importModal.importTemplate')}}</a>
          </i18n>
        </div>
      </div>
    </base-import>
    <!-- 导入联系人 -->

    <!-- start 导出客户 -->
    <base-export-group
      ref="exportPanel"
      method="post"
      :storage-key="exportStorageKey"
      :group="true"
      :alert="exportAlert"
      :columns="exportColumnsData"
      :action="customerListExport"
      :validate="checkExportCount"
      :is-show-export-tip="isOpenData"
      :build-params="buildExportParams"
      :emulate-j-s-o-n="false"
      :needchoose-break="false"
    />
    <!-- end 导出客户 -->

    <base-panel :show.sync="multipleSelectionPanelShow" width="420px">
      <h3 slot="title">
        <span>{{$t('common.base.exportModal.selectedData', { count: multipleSelection.length })}}</span>
        <i
          v-if="multipleSelection.length > 0"
          class="iconfont icon-qingkongshanchu customer-panel-btn"
          @click="toggleSelection()"
          :title="$t('common.base.tip.clearChoseDataTip')"
          data-placement="right"
          v-tooltip
        ></i>
      </h3>

      <div class="customer-selected-panel">
        <div class="customer-selected-tip" v-if="multipleSelection.length <= 0">
          <img :src="noDataImage" />
          <p>{{$t('common.base.tip.noSelectedDataFromList')}}</p>
        </div>
        <template v-else>
          <div class="customer-selected-list">
            <div class="customer-selected-row customer-selected-head">
              <span class="customer-selected-sn">{{$t('common.label.serialNumber')}}</span>
              <span class="customer-selected-name">{{$t('common.label.customer')}}</span>
            </div>
            <div class="customer-selected-row" v-for="c in multipleSelection" :key="c.id">
              <span class="customer-selected-sn">{{c.serialNumber}}</span>
              <span class="customer-selected-name">{{c.name}}</span>
              <el-button
                type="button"
                class="customer-selected-delete"
                @click="cancelSelectCustomer(c)"
              >
                <i class="iconfont icon-fe-close"></i>
              </el-button>
            </div>
          </div>
        </template>
      </div>
    </base-panel>

    <!-- <base-table-advanced-setting ref="advanced" @save="modifyColumnStatus" /> -->
    <biz-select-column
      ref="advanced"
      mode="customer"
      :sotrage-key="'customerV2_select_colum'"
      @save="saveColumnStatus" />

    <customer-tag-edit-dialog
      @onChange='value => emitValueChangedHandler(value)'
      :customer-id='customerIds'
      ref='CustomerTagEditDialogComponent'
    />

    <merge-customer-dialog
       ref='mergeCustomerDialog'
      pageType="list"
      @saveSuccess="saveSuccess"
    />

    <!-- 连接器明细弹窗 -->
    <connector-table-dialog ref="connectorDialogRef" />
    <!-- 新建智能计划弹窗 -->
    <createSmartPlanDialog :customers="multipleSelection" ref="createSmartPlanDialog" />
    <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
    <!-- 客户保存 -->
    <base-save 
    ref="customerSaveRef"
    :has-save="!!(currentView && currentView.viewId && currentView.authEdit)"
    module="customer"
    :current-view="currentView"
    @save="handleViewportSave"
    />
  </div>
</template>

<script>
import { t } from '@src/locales'
// pageDes 客户列表
import { isOpenData, openAccurateTab } from '@src/util/platform'
import _, { isEmpty, cloneDeep } from 'lodash';
import BatchEditingCustomerDialog from './operationDialog/BatchEditingCustomerDialog.vue';
import BatchRemindingCustomerDialog from './operationDialog/BatchRemindingCustomerDialog.vue';
import BatchUpdateCustomerDialog from './operationDialog/BatchUpdateCustomerDialog.vue';
import CustomerTagEditDialog from '@src/modules/customer/view/components/CustomerTagEdit/CustomerTagEditDialog.tsx'
import SendActivityResearch from '@src/modules/customer/components/SendActivityResearch/index.vue'
import MergeCustomerDialog from '@src/modules/customer/list/operationDialog/MergeCustomerDialog.vue';

import {
  getEnabledCardInfo
} from '@src/api/SettingCusProApi';
import * as CustomerApi from '@src/api/CustomerApi.ts';
import { fetchViewportList } from '@src/api/Viewport';
import { checkButtonDisplayed, getRootWindow } from '@src/util/dom';
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import VersionMixin from '@src/mixins/versionMixin/index.ts'
import TeamMixin from '@src/mixins/teamMixin'
import ConnectorMixin from '@src/mixins/connectorMixin'
import ManualTriggerMixin from '@src/mixins/manualTriggerMixin'
import baseSaveShowHandle from '@src/mixins/baseSaveMixin'
/* util */
import { formattedOpenDataTooltip } from '@service/OpenDataService.ts'
import { getFixedColumns, formatFields } from './fields';
import { parse } from '@src/util/querystring';
/* export & import */
import { customerListExport } from '@src/api/Export';
import { customerListImport_1, customerListImportTem_1, customerListImport_2, customerListImportTem_2 } from '@src/api/Import';

import { storageSet, storageGet, sessionStorageGet, sessionStorageRemove } from '@src/util/storageV2';
import { safeNewDate } from '@src/util/time';
import { getSortableMinWidth, defaultTableData } from '@src/util/table';
import { formatDate, randomString, useFormTimezone } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()

// AdvancedSearch
import AdvancedSearch from '@src/component/AdvancedSearch/index.vue'
import AdvancedSearchModal from '@src/component/AdvancedSearch/AdvancedSearchModal.vue'
import ViewportDropdown from '@src/component/ViewportDropdown/index.vue'
import AuthMixin from '@src/mixins/authMixin'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import StorageKeyEnum from '@model/enum/StorageKeyEnum'
import { customerLabel } from '@src/modules/customer/util/customer.js';

import { formatAddress } from 'pub-bbx-utils';
import { fmtDist, setBaseDistValue } from '@src/util/addressUtil';
/* mixin */
import { VersionControlCustomerMixin, VersionControlOtherMixin } from '@src/mixins/versionControlMixin'
import { isNotUndefined } from '@src/util/type';

const link_reg = /((((https?|ftp?):(?:\/\/)?)(?:[-;:&=\+\$]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\?\+=&;:%!\/@.\w_]*)#?(?:[-\+=&;%!\?\/@.\w_]*))?)/g;
import { getOssUrl } from '@src/util/assets'
const noDataImage = getOssUrl('/no_data.png')
import { setServerCach, getServerCach } from '@src/util/serverCach'
import { havePageButtonSetGray } from '@src/util/grayInfo'
import { pageButtonClick, getPageButtonListForView } from '@src/component/compomentV2/buttonSet/common'
import { ButtonGetTriggerModuleEnum, ButtonSetDetailForShowPositionEnum,ButtonSetDetailForButtonConcatEventEnum } from 'pub-bbx-global/pageType/dist/enum/ButtonSetEnum'

export default {
  name: 'customer-list-view',
  mixins: [
    TeamMixin,
    VersionMixin,
    ThemeMixin,
    AuthMixin,
    ConnectorMixin,
    ManualTriggerMixin,
    VersionControlCustomerMixin,
    VersionControlOtherMixin,
    baseSaveShowHandle
  ],
  props: {
    initData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      defaultTableData,
      noDataImage,
      exportStorageKey: StorageKeyEnum.CustomerListExport,
      currentView: null,
      advancedSearchModalVisible: false,
      viewportSearchModel: [],

      isButtonDisplayed: checkButtonDisplayed(),
      buttonStorageModule: 'customerList',
      buttonStorageKey: 'customerListButtonData',
      isOpenData,
      // self state
      selectColumnState: 'customer_list',
      pending: false,
      loadingListData: true,
      multipleSelectionPanelShow: false,
      params: {
        searchCondition: '', //表单内容-附加组件
        orderDetail: {},
        moreConditions: {
          conditions: []
        },
        keyword: '',
        pageNum: 1,
        pageSize: 10
      },
      totalItems: 0,
      multipleSelection: [],
      defaultAddress: [],
      // data from remote
      customers: [],
      columns: getFixedColumns(),
      selectedLimit: 500,
      columnNum: 1,
      fieldInfo: [],
      searchFieldInfo: [],
      customerSelectedTagIdList: [],
      tableKey: this.getTableKey(),
      customerListExport,
      customerListImport_1,
      customerListImportTem_1,
      customerListImport_2,
      customerListImportTem_2,
      enabledCardList: [],
      customerIds: [], // 选中客户的id

      selectId: 'all', // 创建视角
      selectList: [
        // { name: '全部', id: 'all' },
        { name: this.$t('common.task.angle.create'), id: 'create' },
        { name: this.$t('common.task.angle.execute'), id: 'manager' },
        { name: this.$t('common.task.angle.synergy'), id: 'synergies' },
        { name: this.$t('common.customer.myAttention'), id: 'attention' }
      ], // 头部筛选列表
      tableContainerHeight:'440px',
      packUp:true,
      visualAngle:this.$t('common.base.all'),
      preViews:[],

      inCommonUse: [], // 常用字段

      customerTagShow: true,
      pageButtonSetGray:havePageButtonSetGray(),
      pageButtonList:[],
      pageButtonLoading:false,
      tableStatusIsOpen: false,
      ButtonSetDetailForButtonConcatEventEnum
    };
  },
  computed: {
    /**
     * @description 是否是全部编辑权限
    */
    isAllEditedPermission() {
      return this.editedPermission === 3;
    },
    editedPermission() {
      return this.auth.CUSTOMER_EDIT;
    },
    createdPermission() {
      return this.auth.CUSTOMER_CREATE;
    },
    viewedPermission() {
      return this.auth.CUSTOMER_VIEW === 3;
    },
    deletePermission() {
      return this.auth.CUSTOMER_DELETE;
    },
    exportPermission() {
      return this.canCustomerImport || this.canCustomerExport;
    },
    canCustomerImport() {
      return this.auth?.CUSTOMER_IMPORT && this.createdPermission
    },
    canCustomerExport() {
      return this.auth?.CUSTOMER_EXPORT
    },
    selectedIds() {
      return this.multipleSelection.map(c => c.id) || [];
    },
    exportColumns() {
      const fixedFields = [
        {
          field: 'id',
          export: true,
          displayName: t('common.label.customerSystemSerialNumber'),
          fieldName: 'id',
          formType: 'text',
          label: t('common.label.customerSystemSerialNumber')
        }
      ];

      return this.columns.concat(fixedFields).map(c => {
        if (
          c.field !== 'customerAddress'
          && c.field !== 'remindCount'
          && c.field !== 'updateTime'
          && c.formType !== 'info'
          && c.formType !== 'autograph'
        ) {
          c.export = true;
        }

        if (c.field === 'detailAddress') {
          c.exportAlias = 'customerAddress';
        }

        if (c.field === 'customerManagerName') {
          c.exportAlias = 'manager';
        }

        if (c.field === 'name') {
          c.disabled = true;
        }

        if (c.field === 'status') {
          c.label = t('common.label.status');
        }

        return c;
      });
    },
    // 构建导出列
    exportColumnsData(){
      const enabledCardList = JSON.parse(JSON.stringify(this.enabledCardList));
      const exportColumns = {
        value: 'customerExport',
        label: t('common.label.customerInfo'),
        columns: this.exportColumns,
      }

      return [exportColumns, ...enabledCardList].filter(item=>{
        return item.columns && item.columns.length > 0;
      })
    },
    panelWidth() {
      return `${420 * this.columnNum}px`;
    },
    customerConfig() {
      let initData = this.initData;
      return {
        customerAddressConfig: initData.customerAddressConfig,
        customerConfig: initData.customerConfig,
        fieldInfo: (this.fieldInfo || []).sort(
          (a, b) => a.orderId - b.orderId
        )
      };
    },
    auth() {
      return this.initData.auth || {};
    },
    smsRest() {
      return this.initData.smsRest || 0;
    },
    customerListClassNames() {
      return {
        'customer-list-selected-tags' : !isEmpty(this.customerSelectedTagIdList)
      }
    },
    seoFieldInfo(){
      return this.searchFieldInfo.filter(item=>{
        return item.isSearch == 1 && item.formType != 'formula'
      })
    },
    /**
     * @description 是否显示发送邮件
     * 1. 邮件灰度
     * 2. 非纯客服云版本
    */
    isShowEmail() {

      const RootWindow = getRootWindow(window)
      // 邮件灰度
      const emailGray = RootWindow?.grayAuth?.emailCommon || false;

      return emailGray || this._isShowCustomerSendEmail
    },
    createdActivityPermission() {
      return this.auth.ACTIVITIES_CREATE && this.auth.ACTIVITIES_EDIT;
    },
    // 是否显示批量操作
    isShowBatchOperation() {
      // TODO: 暂时不显示了 等容器化按钮组做了再展示
      return false
    },
    /**
     * @description 是否显示发送短信
     * 1. 全部编辑权限
     * 2. 非纯客服云版本
    */
    isShowSendSMS() {
      return this.isAllEditedPermission && this._isShowCustomerSendSMS
    },
    /**
     * @description 是否显示发送活动调研
     * 1. 新建活动调研权限
     * 2. 非纯客服云版本
    */
    isShowSendActivity() {
      return this.createdActivityPermission && this._isShowCustomerSendActivitySurvey
    },
    /**
     * @description 是否显示批量提醒
    */
    isShowCustomerRemind() {
      return this._isShowCustomerRemind
    }
  },
  filters: {
    tagName(value) {
      if (!value || !Array.isArray(value) || !value.length) return '';

      return value
        .filter(tag => tag && tag.tagName)
        .map(tag => tag.tagName)
        .join('，');
    }
  },
  created() {
    // 插入预置视图
    this.selectList.forEach(item=>{
      this.preViews.push({
        viewId: `customer_${item.id}`,
        viewName: item.name,
        searchModel: [{
          fieldName: 'customerCommonSearch',
          operator: '',
          value:{
            visualAngle:item.id
          }
        }],
        authEdit: false,
        visibleType: 1,
        isPre:true
      })
    })
  },
  async mounted() {
    try {
      await this.recoverCommonUse(); // 读取常用条件缓存
    } catch (error) {
      console.error('recoverCommonUse', error);
    }
    try {
      // 获取客户表单字段列表
      let result = await CustomerApi.getCustomerFields({isFromSetting: false});

      if (result.succ) {
        const resultData = result.data || [];
        this.fieldInfo = resultData.map(item => {
          if(item.fieldName === 'name') {
            item['setting'] = {
              ...(item.setting || {}),
              isLimitWord: 1,
              limitWordMax: 200
            }
          }
          return item;
        });
        this.searchFieldInfo = formatFields(result.data?.filter(v => v.fieldName !== 'lmEmail')).filter(f => {

          if(['customerManager', 'synergies'].includes(f.fieldName)) {
            f.emptySearch = true
          }

          if (f.fieldName == 'hasRemind') {
            return this.isShowCustomerRemind
          }

          return f
        });
      }

    } catch(err) {
      console.error('customer list get fields error', err);
    }

    this.getTriggerList(['customer', 'CUSTOMER_ADDITIONAL'])

    this.defaultAddress = setBaseDistValue(this.customerConfig.customerAddressConfig);

    this.revertStorage();
    this.columns = await this.buildTableColumn();
    
    // 如果fieldInfo里面没有parentCustomer字段，需要把colums里面的parentCustomer字段删掉
    if (!this.fieldInfo.find(item => item.fieldName === 'parentCustomer')) {
      this.columns = this.columns.filter(item => item.fieldName!== 'parentCustomer');
    }

    this.buttonStorageData = await this.getButtonLocalStorageData(this.buttonStorageModule, this.buttonStorageKey)
    // 页面参数中有viewNo时说明是复制的视图地址
    const query = parse(window.location.search) || {}
    const viewNo = query.viewNo || ''
    let viewData = {}
    if (viewNo) {
      const list = await fetchViewportList('customer')
      viewData = (list || []).find(item => viewNo === item.viewNo)
    }
    // 页面参数中有viewNo时直接使用chooseView方法，因为viewportSearchModel更新后会执行一遍search
    viewNo && viewData && viewData.searchModel ? this.chooseView(viewData) : this.search();
    this.getEnabledCardInfo();

    this.findFastPageData();
    this.getTenantConfigByCodeList();

    let that_ = this;
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.fasterPage'){
        const {data:parseData, type} = data;
        if(type == 'bbx-faster-customerList'){
          this.findFastPageData(parseData);
        }
      }else if (action == 'shb.frame.activatedPage'){
        // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight()
      }, 500)
    })

    // 对外开放刷新方法，用于其他tab刷新本tab数据
    // TODO: [tab_spec]标准化刷新方式
    window.__exports__refresh = this.search;
    if(this.pageButtonSetGray){
      this.getPageButtonListForView(ButtonGetTriggerModuleEnum.Customer, ButtonSetDetailForShowPositionEnum.PcList,  {}, (list)=>{
        this.pageButtonList = list
      })
    }
  },
  methods: {
    getPageButtonListForView,
    // 自定义按钮点击事件
    handlePageButtonClick(item) {
      pageButtonClick(item, this.multipleSelection, {
        fields: this.fieldInfo,
        multipleSelection: this.multipleSelection,
        js_vm: this,
      }, ()=>{
        this.pageButtonLoading = true
      }, null, ()=>{
        this.pageButtonLoading = false
      })
    },
    /** 打开富文本弹窗 */
    openRichtextVisible(row, column) {
      const richtextId = row?.attribute?.[column.fieldName] || ''
      this.$refs?.baseViewRichTextRef?.openDialog(richtextId)
    },
    /**合并客户 */
    mergeCustomer() {
      const selectionLength = this.multipleSelection?.length ?? 0;
      if(selectionLength < 2) return this.$message.warning(this.$t('customer.mergeCustomer.msg1'));
      if(selectionLength > 5) return this.$message.warning(this.$t('customer.mergeCustomer.msg2'));

      this.$refs.mergeCustomerDialog.selectedCustomers = this.multipleSelection;
      this.$refs.mergeCustomerDialog.open();
    },
    /** 合并成功 */
    saveSuccess() {
      this.multipleSelection = [];
      this.search();
    },
    async getTenantConfigByCodeList() {
      try {
        const params = {
          "codeList": [
            "CUSTOMER_STATUS_HIDDEN"
          ]
        }
        const res = await CustomerApi.getTenantConfigByCodeList(params);
        if(res.status !== 0) return;

        const config = res.data?.[0] || {};
        this.tableStatusIsOpen = config.isOpen || false;
      }catch(e) {
        console.log(e)
      }
    },
    // 点击批量添加标签
    handleClickAddTag() {
      if (!this.multipleSelection.length) {
        return this.$message({
          message: t('customer.batchAddTagNoCustomerTip'),
          type: 'warning'
        });
      }
      this.$refs.CustomerTagEditDialogComponent.show()
    },
    emitValueChangedHandler(value) {
      return value;
    },
    formattedOpenDataTooltip(record = '') {
      return formattedOpenDataTooltip(record || '')
    },
    getRelatedTask(field) {
      return Array.isArray(field) ? field.map(item => item.taskNo).join(',') : '';
    },
    // 处理人员显示
    getUserName(field, value) {
      // 多选
      if(Array.isArray(value)) {
        return value.map(i => i.displayName || i.name).join(',');
      }

      let user = value || {};
      return user.displayName || user.name;
    },
    powerfulSearch() {
      this.params.pageNum = 1;
      // this.params.moreConditions = this.$refs.searchPanel.buildParams();

      this.search();
    },
    showAdvancedSetting() {
      window.TDAPP.onEvent('pc：客户管理-选择列事件');
      this.$refs.advanced.open(this.columns);
    },
    showLatestUpdateRecord(row) {
      if (row.latesetUpdateRecord) return;

      CustomerApi.getUpdateRecord({
        customerId: row.id
      })
        .then(res => {
          if (!res || res.status) return;

          this.customers && this.customers.forEach(c => {
            if (c.id === row.id) {
              this.$set(c, 'latesetUpdateRecord', res.data);
            }
          });
          this.matchSelected();
        })
        .catch(e => console.error('e', e));
    },
    async createCustomerTab(customerId, otherParamsString, needGetAuth = false) {

      if (!this.globalIsHaveCustomerViewDetailAuth) return

      if (needGetAuth) {
        try {
          const res = await CustomerApi.customerCheckAuth({
            customerId,
            from: 'parentCustomer',
          })
          
          if (!res?.result?.check) {
            this.$message.error(this.$t("common.errorMap.code2008.title"));
            return;
          }
        } catch (error) {
          console.log(error);
          return;
        }
      }

      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `customer_view_${customerId}`,
      //   title: '客户详情',
      //   close: true,
      //   url: `/customer/view/${customerId}?noHistory=1${otherParamsString || ''}`,
      //   fromId
      // });

      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params: `noHistory=1${otherParamsString || ''}`,
        fromId
      })
    },
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
      localStorage.setItem(
        'customer_list_advance_search_column_number',
        command
      );
    },
    formatAddress(ad) {
      return fmtDist(ad)
    },
    formatCustomizeAddress(ad) {
      return formatAddress(ad);
    },
    remindSuccess(ids) {
      let tv = false;
      if (!ids || !ids.length) return;

      this.customers.forEach(c => {
        tv = ids.some(id => c.id === id);
        if (!tv) return;
        if (!c.attribute.remindCount) {
          c.attribute.remindCount = 1;
        } else {
          c.attribute.remindCount += 1;
        }
      });
    },
    jumpPage() {
      window.TDAPP.onEvent('pc：客户管理-新建事件');

      // window.location = '/customer/create';
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: 'customer_create',
      //   title: '新建客户',
      //   url: '/customer/create',
      //   reload: true,
      //   close: true,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateCustomer,
        reload: true,
        fromId
      })
    },
    /** 构建客户导出参数 */
    buildExportParams(checkedArr, ids) {
      const { customerExport } = checkedArr;
      // 附加
      let cardFieldChecked = []
      let cardChecked = [];
      for (let key in checkedArr) {
        if (key.indexOf('annexChecked') !== -1) {
          cardFieldChecked = [...cardFieldChecked, ...checkedArr[key]];
          if(checkedArr[key].length > 0) cardChecked.push(key.split('#')[1]);
        }
      }

      // 附加信息
      let export_card_field = cardFieldChecked.length ? this.exportData('cardFieldChecked', cardFieldChecked) : cardFieldChecked

      let exportAll = !ids || ids.length == 0;
      let exportSearchModel = exportAll
        ? {
          ...this.buildParams(),
          exportTotal: this.totalItems
        }
        : { exportTotal: ids.length };

      let params = {
        customerChecked: this.exportData('customerExport', customerExport).join(','),
        data: exportAll ? '' : ids.join(','),
        exportSearchModel: JSON.stringify(exportSearchModel)
      }

      params['cardChecked'] = cardChecked.join(',');
      params['cardFieldChecked'] = export_card_field.filter(item => {
        return item;
      }).join(',');

      return params;
    },
    /** 导出客户 */
    exportCustomer(exportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}${t('common.base.customerData')}.xlsx`;
      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(t('common.base.tip.exportNoChoice'));
        ids = this.selectedIds;
      }
      this.$refs.exportPanel.open(ids, fileName);
    },
    /** 检测导出条数 */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.totalItems > max
        ? t('common.base.tip.exportLimit', { max })
        : null;
    },
    importSucc() {
      // console.log('importSucc');
      // this.search();
    },
    revertStorage() {
      const { pageSize, column_number } = this.getLocalStorageData();
      if (pageSize) {
        this.params.pageSize = pageSize;
      }
      if (column_number) this.columnNum = Number(column_number);
    },
    search() {
      this.$nextTick(()=>{
        // 滚动至表格顶部
        this.$refs.multipleTable?.$refs?.bodyWrapper?.scrollTo(0, 0)
      })
      const params = this.buildParams();

      this.loadingListData = true;

      return CustomerApi.getCustomerSearchList(params)
        .then(res => {
          if (res.code !== 0 || !res.result?.list) {
            this.customers = [];
            this.totalItems = 0;
            this.params.pageNum = 1;
          } else {
            const { total, pageNum, list } = res.result || {};

            this.customers = disposeFormListViewTime(list, this.columns).map(c => {
              c.pending = false;
              return c;
            });
            this.totalItems = total;
            this.params.pageNum = pageNum;
            this.matchSelected(); // 把选中的匹配出来
          }

          return res.result || {};
        })
        .then(() => {
          this.$refs.customerListPage.scrollTop = 0;
          this.loadingListData = false;
          // 原先用的是getTableKey，经月初确认，该函数作用是保证客户标签的展示，但是列表重置会导致表头排序状态丢失，所以换种方式
          this.refreshCustomerTag()
          // 因为matchSelected是toggle，没有明确的匹配，所以只能用一个，之前是因为有getTableKey所以加的这个，现在不能留着~
          // this.$nextTick(() => {
          //   this.matchSelected(); // 把选中的匹配出来
          // })
        })
        .catch(err => {
          this.loadingListData = false;
          console.error('err', err);
        });
    },
    // 重置客户标签组件，刷新客户标签
    refreshCustomerTag() {
      this.customerTagShow = false
      this.$nextTick(() => {
        this.customerTagShow = true
      })
    },
    buildParams() {
      const systemTypes = ['customerManager', 'createUser', 'synergies', 'tags', 'addressDetail']
      const sm = Object.assign({}, this.params);
      let params = {
        searchCondition: sm.searchCondition,
        keyword: sm.keyword,
        pageSize: sm.pageSize,
        pageNum: sm.pageNum,
        tenantTagIdList: this.customerSelectedTagIdList,
        systemConditions:sm.systemConditions || [],
        conditions:sm.conditions || []
      };

      if (Object.keys(sm.orderDetail || {}).length) {
        params.orderDetail = sm.orderDetail;
      }

      params.systemConditions.forEach(item=>{
        if(systemTypes.indexOf(item.property) > -1){
          item.jsonDataField = item.property
          if(item.property == 'tags'){
            item.property = 'id'
          }else if(item.property == 'addressDetail'){
            item.property = 'address'
            item.jsonDataField = 'mainAddress'
          }else{
            item.property = 'userId'
          }
        }
      })

      // if (Object.keys(sm.orderDetail || {}).length) {
      //   params.orderDetail = sm.orderDetail;
      // }

      // if (
      //   Object.keys(sm.moreConditions).length > 1
      //   || sm.moreConditions.conditions.length
      // ) {
      //   params = {
      //     ...params,
      //     ...sm.moreConditions
      //   };
      // }

      // 创建视角赋值
      params.mbSearchType = this.selectId

      return params;
    },
    cancelSelectCustomer(customer) {
      if (!customer || !customer.id) return;
      this.multipleSelection = this.multipleSelection.filter(
        ms => ms.id !== customer.id
      );
      this.toggleSelection([customer]);
    },
    toggleStatus(row) {
      window.TDAPP.onEvent('pc：客户管理-状态开启事件');

      const ns = row.status ? 0 : 1;
      row.pending = true;
      const params = {
        id: row.id,
        status: ns
      };

      this.$http
        .post('/customer/changeState', params, false, { cancelable: false })
        .then(res => {
          row.pending = false;

          if (res.status) {
            return this.$platform.alert(res.message);
          }

          this.customers.forEach(c => {
            if (c.id === row.id) {
              c.status = ns;
            }
          });
        })
        .catch(err => {
          row.pending = false;
          console.error('toggleStatus catch err', err);
        });
    },
    sortChange(option) {
      /**
       * 目前情况：
       * 所有字段理应后台获取，但是获取的所有字段中没有 createTime
       *
       */
      try {
        const { prop, order } = option;
        if (!order) {
          this.params.orderDetail = {};
          return this.search();
        }

        let isSystem = ['createTime', 'updateTime', 'serialNumber'].includes(prop) ? 1 : 0

        let sortModel = {
          isSystem,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          column: isSystem ? `customer.${prop}` : prop
        };

        const sortedField = this.customerConfig.fieldInfo.filter(sf => sf.fieldName === prop)[0] || {};

        if (prop === 'createTime' || prop === 'updateTime' || sortedField.formType === 'date' || sortedField.formType === 'datetime') {
          sortModel.type = 'date';
        } else {
          sortModel.type = sortedField.formType;
        }

        this.params.orderDetail = sortModel;

        this.search();
      } catch (e) {
        console.error('e', e);
      }
    },
    jump(pageNum) {
      this.params.pageNum = pageNum;
      this.search();
    },
    handleSizeChange(pageSize) {
      this.saveDataToStorage('pageSize', pageSize);
      this.params.pageNum = 1;
      this.params.pageSize = pageSize;
      this.search();
    },
    // select customer
    handleSelection(selection) {
      let tv = this.computeSelection(selection);
      let original = this.multipleSelection.filter(ms =>
        this.customers.some(cs => cs.id === ms.id)
      );
      let unSelected = this.customers.filter(c =>
        original.every(oc => oc.id !== c.id)
      );

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(t('common.base.tip.maxDataCanChooseTips', { data1: this.selectedLimit }));
      }
      this.multipleSelection = tv;

      this.customerIds = [];
      this.multipleSelection.forEach(item => {
        this.customerIds.push(item.id)
      })

      this.$refs.baseSelectionBar?.openTooltip();
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
    computeSelection(selection) {
      let tv = [];
      tv = this.multipleSelection.filter(ms =>
        this.customers.every(c => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);
      return tv;
    },
    toggleSelection(rows) {
      let isNotOnCurrentPage = false;
      let row = undefined;

      if (rows) {
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.customers.every(item => {
            return item.id !== row.id;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    // list method end

    // operation dialog
    openDialog(category) {
      if (category === 'sendMessage') {
        window.TDAPP.onEvent('pc：客户管理-发送短信事件');

        this.$refs.messageDialog.openSendMessageDialog();
      }
      if (category === 'sendEmail') {
        this.$refs.emailDialog.openDialog();
      }
      if (category === 'edit') {
        window.TDAPP.onEvent('pc：客户管理-批量编辑事件');

        this.$refs.batchEditingCustomerDialog.open();
      }
      if (category === 'remind') {
        window.TDAPP.onEvent('pc：客户管理-批量提醒事件');

        this.$refs.batchRemindingCustomerDialog.openBatchRemindingCustomerDialog();
      }
      if (category === 'importCustomer') {
        this.$refs.importCustomerModal.open();
      }
      if (category === 'importLinkman') {
        this.$refs.importLinkmanModal.open();
      }
      if (category === 'update') {
        // if (!this.multipleSelection || !this.multipleSelection.length) {
        //   return this.$platform.alert('您尚未选择数据，请选择数据后点击批量更新');
        // }
        this.$refs.batchUpdateCustomerDialog.openBatchUpdateCustomerDialog();
      }
    },
    async deleteCustomer() {
      window.TDAPP.onEvent('pc：客户管理-删除事件');

      if (!this.multipleSelection.length) {
        return this.$platform.alert(t('common.placeholder.selectNeedDelCustomer'));
      }
      try {
        // fuck
        const result = await this.$platform.confirm(t('common.base.tip.confirmDelCustomer'));
        if (!result) return;

        this.loadingListData = true;
        const params = { ids: this.selectedIds.join(',') };
        this.$http
          .post('/customer/delete', params)
          .then(res => {
            if(res.succ == 'false') return this.$platform.alert(res.message);

            this.multipleSelection = [];
            // 删除之后留1S延迟给es同步
            setTimeout(()=>{
              this.search();
            }, 1000)
          })
          .catch(err => console.error('deleteCustomer err', err))
          .finally(() => {
            this.loadingListData = false;
          });
      } catch (e) {
        console.error('deleteCustomer catch error', e);
        this.loadingListData = false;
      }
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus (event) {
      let columns = event.data || [];

      this.columns = [];

      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.saveSuccess'));
    },
    saveColumnStatusToStorage () {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null
      // 判断是否存储选择列
      const columnsList = this.columns.map((c) => ({
        field: c.field,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft
      }));

      if(localStorageData[this.currentView?.viewId]){
        try{
          localStorageData[this.currentView?.viewId][
            `${this.selectColumnState}`
          ] = columnsList;
          columnsStatus = localStorageData[this.currentView?.viewId];
        }catch(err){
          console.error(err)
        }
      }else if (localStorageData.columnStatus) {
        localStorageData.columnStatus[
          `${this.selectColumnState}`
        ] = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = {
          [`${this.selectColumnState}`]: columnsList,
        };
      }
      if(this.currentView?.viewId){
        this.saveDataToStorage(this.currentView?.viewId, columnsStatus)
      }else{
        this.saveDataToStorage('columnStatus', columnsStatus); // 默认选择列保存
      }
    },
    // columns
    // common methods
    async getLocalStorageData() {
      let dataStr = storageGet('customerListData') || '{}';
      if(dataStr === '{}'){
        dataStr = await getServerCach('customerListData', {}, 'customerList', 'customerListData') || {}
        dataStr = JSON.stringify(dataStr)
        storageSet('customerListData', dataStr)
      }
      return JSON.parse(dataStr);
    },
    async saveDataToStorage(key, value) {
      const data = await this.getLocalStorageData();
      data[key] = value;

      setServerCach('customerListData', data, 'customerList', 'customerListData')
      storageSet('customerListData', JSON.stringify(data))
    },
    async buildTableColumn() {
      const localStorageData = await this.getLocalStorageData();
      // let columnStatus = localStorageData.columnStatus && localStorageData.columnStatus[this.selectColumnState]
      let columnStatus = []
      if(this.currentView?.viewId && localStorageData[this.currentView?.viewId]){
        columnStatus = localStorageData[this.currentView?.viewId][this.selectColumnState]
      }else{
        columnStatus = localStorageData.columnStatus && localStorageData.columnStatus[this.selectColumnState]
      }
      columnStatus = columnStatus || [];
      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col) => (acc[col.field] = col) && acc, {});

      const versionShowFieldNameMap = {
        customerTag: this._isShowCustomerTag,
        remindCount: this.isShowCustomerRemind,
        lmEmail: this._isShowEmail
      }

      let baseColumns = getFixedColumns().filter(f => {

        const fieldName = f?.fieldName || '';
        const isShow = versionShowFieldNameMap[fieldName]

        if (isNotUndefined(isShow)) {
          return isShow
        }

        return f

      });
      let dynamicColumns = this.customerConfig.fieldInfo
        .filter(
          f =>
            !f.isSystem
            && f.formType !== 'attachment'
            && f.formType !== 'separator'
            && f.formType !== 'info'
            && f.formType !== 'autograph'
        )
        .map(field => {
          let sortable = false;
          let minWidth = null;

          if (['date', 'datetime', 'number'].indexOf(field.formType) >= 0) {
            sortable = 'custom';
            minWidth = 100;
          }

          if (field.displayName.length > 4) {
            minWidth = field.displayName.length * 20;
          }

          if (sortable && field.displayName.length >= 4) {
            minWidth = getSortableMinWidth(field)
          }

          if (field.formType === 'datetime') {
            minWidth = Math.max(150, minWidth);
          }

          return {
            ...field,
            label: field.displayName,
            field: field.fieldName,
            formType: field.formType,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            sortable,
            isSystem: field.isSystem
          };
        });

      const mergeColumns = [...baseColumns, ...dynamicColumns];

      let _columns = mergeColumns.map(col => {
        let show = col.show === true;
        let { width } = col;
        let localField = localColumns[col.field];
        let fixLeft = localField?.fixLeft || null;
        if (null != localField) {
          width = typeof localField.width == 'number'
            ? `${localField.width}px`
            : `${localField.width}`.indexOf('px') ? localField.width : '';
          show = localField.show !== false;
        }

        col.show = show;
        col.width = width;
        col.type = 'column';
        col['fixLeft'] = fixLeft && 'left'
        return col;
      });

      let columns = []
      // 选择列按照缓存排序
      if (columnStatus.length > 0) {
        columnStatus.forEach(item => {
          _columns.forEach(subItem => {
            if (item.field === subItem.field) {
              columns.push(subItem)
            }
          })
        })
        _columns.forEach(item => {
          if(!columns.find(v => v.field === item.field)) {
            columns.push(item)
          }
        })
      } else {
        columns = _columns;
      }

      return columns;
    },
    resetParams() {
      window.TDAPP.onEvent('pc：客户管理-重置事件');
      // this.$refs.searchPanel.resetParams();
      // this.$refs.customerFilterViewRef.reset();

      this.params = {
        searchCondition:'',
        keyword: '',
        pageNum: 1,
        pageSize: this.params.pageSize,
        orderDetail: {},
        conditions:[],
        systemConditions:[],
        // moreConditions: {
        //   conditions: []
        // }
      };
      this.chooseView();
      // this.search();
    },
    // match data
    matchSelected() {
      if (!this.multipleSelection.length) return;
      const selected = this.customers.filter(c => {
        if (this.multipleSelection.some(sc => sc.id === c.id)) {
          this.multipleSelection = this.multipleSelection.filter(
            sc => sc.id !== c.id
          );
          this.multipleSelection.push(c);
          return c;
        }
      }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },
    panelSearchAdvancedToggle() {
      window.TDAPP.onEvent('pc：客户管理-高级搜索事件');
      // this.$refs.searchPanel.open();
      this.$nextTick(() => {
        let forms = document.getElementsByClassName('advanced-search-form');
        for (let i = 0; i < forms.length; i++) {
          let form = forms[i];
          form.setAttribute('novalidate', true);
        }
      });
    },
    // TalkingData事件埋点
    trackEventHandler(type) {
      if (type === 'search') {
        window.TDAPP.onEvent('pc：客户管理-搜索事件');
        return;
      }
      if (type === 'moreAction') {
        window.TDAPP.onEvent('pc：客户管理-更多操作事件');
        return;
      }
    },
    openOutsideLink(e) {
      let url = e.target.getAttribute('url');
      if (!url) return;
      if (!/http/gi.test(url))
        return this.$platform.alert(t('common.base.tip.confirmHttpProtocol'));
      this.$platform.openLink(url);
    },
    buildTextarea(value) {
      let textareaValue = value
        ? value.replace(link_reg, (match) => {
          return `<a href="javascript:;" target="_blank" url="${match}">${match}</a>`
        })
        : '';

      return textareaValue.replace(/\s/g, '&nbsp;');
    },
    getRowKey(row) {
      return row.id;
    },
    searchCustomerTags(custoemrTags) {
      if (_.isEqual(this.customerSelectedTagIdList, custoemrTags)) return

      this.customerSelectedTagIdList = custoemrTags
      this.search()
    },
    getTableKey() {
      this.tableKey = randomString()
    },
    wxchatButtonClickHandler(customerId) {
      this.createCustomerTab(customerId, '&active=contact')
    },
    /**
     * @des 表单拖拽钩子函数
     */
    headerDragend (newWidth, oldWidth, column, event) {
      let data = this.columns
        .map((item) => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map((item) => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus (event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach((col) => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },
    /**
     * 导出数据
     */
    exportData(type, list = []) {
      const export_list = this.exportColumnsData
      if (type === 'cardFieldChecked') {
        let cardField = []
        export_list.filter((item, index) => {
          return item.value !== 'customerExport';
        }).forEach(v => {
          v.columns.forEach(item => {
            cardField.push(item)
          })
        })
        return cardField.map(v => {
          let bool = list.some(item => {
            if (v.exportAlias) {
              return v.exportAlias === item
            }
            return v.fieldName === item

          })
          if (bool) {
            return v.exportAlias ? v.exportAlias : v.fieldName
          }
        }).filter(item => {
          return item
        })
      }

      let xlistColumns = []
      export_list.forEach((xlist, i) => {
        if(xlist.value === type) xlistColumns = xlist.columns
      })
      
      return xlistColumns.map(v => {
        let bool = list.some(item => {
          if (v.exportAlias) {
            return v.exportAlias === item
          }
          return v.fieldName === item

        })
        if (bool) {
          return v.exportAlias ? v.exportAlias : v.fieldName
        }
      }).filter(item => {
        return item
      })
    },
    /**
     * @description 导出提示
     */
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    // 获取附加组件
    async getEnabledCardInfo(){
      try{
        let { result = [], code, message } = await getEnabledCardInfo({cardType: 'customer'});
        if(code === 0){
          this.enabledCardList = result.filter(item => item && item.specialfrom !== '连接器').map((item, index)=>{

            item.fields = [...(item?.fields || []), ...[{displayName: t('common.label.operator'),
              fieldName: `cu_${item.id}`}, {displayName: t('common.label.operationTime'),
              fieldName: `ct_${item.id}`}]];

            let columns = item.fields.map((v, i) => {
              return {
                export: true,
                label: v.displayName,
                exportAlias: v.fieldName,
                ...v,
              };
            });

            return {
              value: `annexChecked#${item.id}`,
              label: t('common.label.addOnsName', { name: item.name }),
              inputType: item.inputType,
              columns: columns.filter(f => !['attachment', 'separator', 'autograph', 'info'].includes(f.formType)),
            };
          })
        }else{
          this.$message.error(message);
        }
      }catch(err){
        console.error(err);
      }
    },

    /**
     * 创建视角
     */
    createPerspective(item){
      this.selectId = item.id;
      this.visualAngle = item.name
      this.params.pageNum = 1;
      this.search();
    },
    /**
     * @des 提供给快捷筛选视图的方法
     */
    fasterFilterList(key){
      try {
        let item = this.selectList.find(item=>item.id == key);
        this.createPerspective(item)
      } catch (error) {
        console.warn(error, 'fasterFilterList error try catch');
      }
    },
    /**
     * @des 查询是否有查询参数
     */
    findFastPageData(data){
      try {
        let parseData = sessionStorageGet('bbx-faster-customerList');
        if(parseData){
          sessionStorageRemove('bbx-faster-customerList');
        }
        const {filterData} = data || JSON.parse(parseData);
        this.fasterFilterList(filterData.createView);
      } catch (error) {
        console.warn(error, 'findFastPageData error try catch');
      }
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
		 knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 24 - 16;
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },

    // 视图高级搜索改版
    // 高级搜索 ——> 点击搜索按钮
    async handleAdvancedSearch({searchModel = {}, searchList = []}){
      this.params.pageNum = 1;
      this.params = {...this.params, ...searchModel}
      // minix,混入名为baseSaveShowHandle
      let searchParamsPeer = this.handleShowSave(searchList);

      await this.search()

      if(this.$refs.customerSaveRef && typeof this.$refs.customerSaveRef.open === 'function') {
        this.$refs.customerSaveRef.open(searchParamsPeer, searchList);
      };
    },
    // 处理视图
    genViewport(_v){
      if(!_v || !_v.searchModel) return null
      const viewport = cloneDeep(_v);
      return viewport
    },
    // 选择视图
    chooseView(_v){
      // this.resetParams()
      this.currentView = this.genViewport(_v); // 视图设为当前视图
      this.viewportSearchModel = this.currentView?.searchModel || [];
      // this.resetParams(); // 重置条件并搜索
      if(this.currentView?.searchModel[0]?.fieldName === 'customerCommonSearch'){
        // 外面固定条件截取
        const formData = this.currentView.searchModel.shift();
        if(formData?.value?.visualAngle){
          let item = this.selectList.find(item=>item.id == formData?.value?.visualAngle);
          if(item){
            this.selectId = formData?.value?.visualAngle
            this.visualAngle = item.name
          }
        }
      }else{
        this.selectId = 'all'
        this.visualAngle = this.$t('common.base.all')
      }
    },

    // 从视图列表 ——> 编辑、新建视图
    editViewByViewport(_v){
      const viewport = this.genViewport(_v);
      this.$refs.advancedSearchModalRef.open(viewport)
    },

    // 从高级筛选新建视图
    createViewBySearchModel(searchModel) {
      this.$refs.advancedSearchModalRef.open({searchModel})
    },

    // 从高级筛选更新视图
    updateViewBySearchModel(searchModel) {
      const viewportData = {
        ...this.currentView,
        searchModel,
      }
      this.$refs.advancedSearchModalRef.open(viewportData)
    },

    /**
     * 视图保存成功 更新选中视图
     * @param {Object} _v 视图信息
     */
    handleViewportSave(_v){
      if(!_v) return;
      this.chooseView(_v); // 选中当前视图
      this.$refs.viewportListRef.refresh(_v.viewId); // 刷新视图列表 并选中
    },

    // 保存视图之前，存入外部固定条件到视图中
    beforeSaveView(){
      const value = {
        visualAngle: this.selectId,
      }
      return [
        {fieldName: 'customerCommonSearch', operator: '', value },
      ]
    },

    /**
     * 常用字段切换
     * @param {*} fieldName
     * @param {*} isChecked
     */
    changeCommonUse({fieldName, isChecked}){
      const inCommonUseSet = new Set(this.inCommonUse)
      if(isChecked){
        inCommonUseSet.add(fieldName)
      }else {
        inCommonUseSet.delete(fieldName);
      }
      this.inCommonUse = Array.from(inCommonUseSet);
      const storageKey = 'advanced-search-commonUse';
      this.saveDataToStorage(storageKey, this.inCommonUse);
    },

    /**
     * 恢复常用字段
     */
    async recoverCommonUse(){
      try {
        const storageKey = 'advanced-search-commonUse';
        const data = await this.getLocalStorageData()
        this.inCommonUse = data[storageKey] || [];
      } catch (error) {
        console.error('获取常用字段 recoverCommonUse', error);
        return Promise.reject(error)
      }
    },
    customerLabel,
    // 呼叫中心来源数据
    callCenterSourceData(scope){
      return {
        sourceTypeId:scope.row.id,
        sourceType:'customer',
      }
    },
    handleCommand(command) {
      if (command == 'smartPlan') {
        if (!this.multipleSelection.length) {
          return this.$platform.alert(this.$t('common.placeholder.selectCustomer'))
        }
        this.$refs.createSmartPlanDialog.open()
      } else if (command.type == 'trigger') {
        if (!this.multipleSelection.length) {
          return this.$platform.alert(this.$t('common.placeholder.selectCustomer'))
        }
        this.handleManualTrigger(command.id, this.multipleSelection.map(item => item.id))
      } else if (command == 'sendMessage') {
        this.$track.clickStat(this.$track.formatParams('SEND_MESSAGE'))
        this.openDialog('sendMessage')
      } else if (command == 'sendEmail') {
        this.$track.clickStat(this.$track.formatParams('SEND_EMAIL'))
        this.openDialog('sendEmail')
      } else if (command == 'sendActivity') {
        this.$track.clickStat(this.$track.formatParams('SEND_ACTIVITY_RESEARCH'))
        this.$refs.sendActivityResearch.handleCreate()
      } else if (command == 'remind') {
        this.$track.clickStat(this.$track.formatParams('BATCH_REMIND'))
        this.openDialog('remind')
      } else if (command == 'edit') {
        this.$track.clickStat(this.$track.formatParams('BATCH_EDIT'))
        this.openDialog('edit')
      } else if (command == 'delete') {
        this.$track.clickStat(this.$track.formatParams('DELETE'))
        this.deleteCustomer()
      }
    },
  },
  watch:{
    currentView:{
      async handler(){
        this.columns = await this.buildTableColumn();
      },
      immediate:true
    }
  },
  components: {
    [BatchEditingCustomerDialog.name]: BatchEditingCustomerDialog,
    [BatchRemindingCustomerDialog.name]: BatchRemindingCustomerDialog,
    [BatchUpdateCustomerDialog.name]: BatchUpdateCustomerDialog,
    CustomerTagEditDialog,
    AdvancedSearch, // 高级筛选
    AdvancedSearchModal, // 视图编辑弹框
    ViewportDropdown,
    [SendActivityResearch.name]: SendActivityResearch,
    [MergeCustomerDialog.name]: MergeCustomerDialog,
  }
};
</script>

<style lang="scss" scoped>
  .common-list-table {
    ::v-deep .el-table__body {
      width: 100%;
      table-layout: fixed !important;
    }
  }
  // .base-switch{
  //   font-size: 20px;
  //   ::v-deep .el-switch__core {
  //     cursor: default !important;
  //   }
  // }
</style>
<style lang="scss">

html,
body {
  height: 100%;
}

.level-padding {
  padding: 0 5px;
}

.advanced-search-linkman {
  .el-select-dropdown__item {
    height: 50px;
    padding: 5px 20px;
    p {
      margin: 0;
      line-height: 20px;
    }
  }
}

.customer-advance-setting .el-dropdown-menu__item {
  width: 80px;
  text-align: center;
}

.customer-list-container {
  height: 100%;
  overflow: auto;
  padding: 10px;

  .panel-title {
    font-size: 16px;
    line-height: 60px;
    padding: 0 25px;
    color: rgb(132, 138, 147);
    border-bottom: 1px solid rgb(242, 248, 247);
    font-weight: normal;
    display: flex;
    justify-content: space-between;
    .iconfont:hover {
      cursor: pointer;
    }
  }
  .action-button-group {
    display: flex;
  }
}

// search
.customer-list-search-group-container {
  flex-direction: column;
  .advanced-search-function,
  .base-search {
    background: #fff;
    border-radius: 4px;
  }

  .base-search {
    font-size: 14px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
    // padding: 16px;

    .customer-list-base-search-group {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .el-input {
        width: 400px;
        input {
          border-radius: 4px 0 0 4px
        }
      }

      a {
        line-height: 33px;
      }
    }

    .advanced-search-visible-btn {
      font-size: 14px;
      height: 32px;
      line-height: 32px;
      @include fontColor();
      border-color: $color-primary;
      background: #fff;
      // padding: 0 13px;
      white-space: nowrap;
      margin-left: 12px;
      &:hover {
        cursor: pointer;
      }
    }
  }

  .advanced-search-form {
    overflow: auto;
    padding: 10px 0 63px 0;
    height: calc(100% - 51px);

    .form-item-container {
    }

    .two-columns {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        width: 50%;
      }
    }

    .el-form-item {
      .el-form-item__content,
      .el-select,
      .base-dist-picker,
      .el-cascader,
      .el-date-editor {
        width: 290px;
      }
    }

    .advanced-search-btn-group {
      display: flex;
      justify-content: flex-end;
      width: 100%;
      position: absolute;
      bottom: 0px;
      background: #fff;
      padding: 15px 20px;

      .base-button {
        margin: 0 10px;
      }
    }
  }

  .advanced-search-function {
    margin-top: 10px;
    padding-bottom: 10px;

    h4 {
      border-bottom: 1px solid #f4f4f4;
      padding: 10px;
    }

    .el-row {
      padding: 5px 0;
    }
    .input-label {
      text-align: right;
      line-height: 32px;
      padding-right: 0;
    }
  }
}

// list
.customer-list-component {
  margin-top: 10px;

  .customer-table {
    border: none;

    .sample-tooltip-container {
      width: 100%;
    }

    &:before {
      height: 0;
    }

    .customer-table-header th {
      background: #FAFAFA;
      color: $text-color-primary;
      font-weight: normal;
    }

    .view-detail-btn {
      @include fontColor();
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .view-detail-btn-disabled {
      color: #666;
      cursor: default;
    }

    .select-column .el-checkbox {
      position: relative;
      top: 3px;
    }
  }

  .table-footer {
    display: flex;
    justify-content: space-between;
    padding: 0px 10px 10px 10px;
    background: #fff;
    border-radius: 0 0 4px 4px;

    .list-info {
      font-size: 13px;
      line-height: 32px;
      margin: 0;
      color: #767e89;

      .iconfont {
        position: relative;
        top: 1px;
      }
    }

    .el-pagination__jump {
      margin-left: 0;
    }
  }
}

.customer-panel-btn {
  float: right;
  cursor: pointer;
  font-size: 14px;
  margin-right: 5px;

  &:hover {
    @include fontColor();
  }
}

// -------- customer selected panel --------
.customer-selected-count {
  @include fontColor();
  padding: 0 3px;
  width: 15px;
  text-align: center;
  cursor: pointer;
  font-size: 13px;
}

.customer-selected-panel {
  font-size: 14px;
  height: calc(100% - 51px);

  .customer-selected-tip {
    padding-top: 80px;

    img {
      display: block;
      width: 160px;
      margin: 0 auto;
    }

    p {
      text-align: center;
      color: $text-color-regular;
      margin: 8px 0 0 0;
      line-height: 20px;
    }
  }

  .customer-selected-list {
    height: 100%;
    padding: 10px;
    overflow-y: auto;

    .customer-selected-row {
      display: flex;
      flex-flow: row nowrap;
      line-height: 36px;
      border-bottom: 1px solid #ebeef5;
      font-size: 13px;

      &:hover {
        background-color: #f5f7fa;

        .customer-selected-delete {
          visibility: visible;
        }
      }
    }

    .customer-selected-head {
      background-color: #f0f5f5;
      color: #333;
      font-size: 14px;
    }

    .customer-selected-sn {
      padding-left: 10px;
      width: 150px;
      @include text-ellipsis;
    }

    .customer-selected-name {
      padding-left: 10px;
      flex: 1;
      @include text-ellipsis;
    }

    .customer-selected-delete {
      width: 36px;
    }

    .customer-selected-row button.customer-selected-delete {
      padding: 0;
      width: 36px;
      height: 36px;
      border: none;
      background-color: transparent;
      outline: none;
      color: #646b78;
      visibility: hidden;

      i {
        font-size: 14px;
      }

      &:hover {
        color: #e84040;
      }
    }
  }
}

// operation
.customer-columns-dropdown-menu {
  max-height: 300px;
  overflow: auto;
  .el-dropdown-menu__item {
    padding: 0;
  }
  .el-checkbox {
    width: 100%;
    padding: 5px 15px;
    margin: 0;
  }
}

.operation-bar-container {
  background: #fff;
  border-radius: 4px 4px 0 0;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 16px 16px 0;

  .top-btn-group {
    & > * {
      margin-left: 0;
      margin-right: 12px;
      margin-bottom: 4px;
    }
  }

  .action-button-group {
    padding-right: 0;
    .el-dropdown-link {
      white-space: nowrap;
    }
    .base-button {
      margin-left: 5px;
    }
  }

  .el-dropdown-btn {
    line-height: 32px;
    display: inline-block;
    background-color: transparent;
    outline: none;
    .iconfont {
      margin-left: 5px;
    }

    &:hover {
      cursor: pointer;
      background-color: transparent;
    }
  }
}
// superscript
.customer-name-superscript-td {
  padding: 0 !important;
  & > div {
    height: 43px;
    line-height: 43px !important;
    a {
      display: inline-block;
      height: 43px;
      line-height: 43px;
    }
  }
  // 此属性是为了兼容Safari
  max-width: 10000px;
}

.customer-name-block {
  display: flex;
  align-items: center;
}

.customer-name-wx {
  width: calc(100% - 50px);
}

.customer-list-component {
  .el-table__body-wrapper {
    .base-tags {
      // 此属性是为了兼容Safari
      max-width: 10000px;
    }
  }
}

.customer-list-selected-tags {
  .biz-customer-tag-select {
    .el-dropdown-link {
      color: $color-primary;
    }
  }
}

.el-tooltip__popper {
  z-index: 3000;
}
</style>
<style lang="scss" scoped>
  .list-search-group-container {
    padding: 0 16px 0 0;
  }
  .list-header-seach {
    margin: 16px 0;
    display: flex;
    align-items: center;
    padding-left: 16px;
  }
  .list-header-nav {
    padding-bottom: 10px;
    .list-header-filter-item {
      display: flex;
    }
    > div {
      position: relative;
      cursor: pointer;
      .state {
        padding-top: 4px;
        padding-left: 11px;
        width: 90px;
        font-weight: 500;
        color: #A7B5B5;
        font-size: 14px;
      }
      .element-icon {
        position: absolute;
        right: 12px;
        top: 6px;
        span {
          color: rgba(0, 0, 0, 0.65);
        }
      }
      .list {
        width: 90%;
        overflow: hidden;
        .list-item {
          align-items: center;
          display: flex;
          flex-wrap: wrap;
          > div {
            font-size: 13px;
            width: 130px;
            height: 32px;
            overflow-y: hidden;
            color: #808080;
            line-height: 32px;
            padding: 0 12px;
            &:hover {
              color:$color-primary;

            }
          }
          .item-selected {
            color: $color-primary-light-6;
            padding: 0;
            .actived {
             background: $color-primary-light-1;
              border-radius: 4px;
              border: 1px solid $color-primary-light-2;
              padding: 3px 12px;
            }
          }
        }
      }
    }
  }

  .link {
    color: $color-primary-light-6;
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }

.task-common-advanced-search-form {
  margin-bottom: 16px;

  .search-row {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    .search-row__label {
      margin-right: 10px;
      width: 70px;
    }
    .search-row__content {
      flex: 1;
      display: flex;
      align-items: center;
    }
    .__tag {
      margin-right: 8px;
      flex: 0 0 auto;
      max-width: 180px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
}

</style>
<style lang="scss">
  @import "@src/assets/scss/common-list.scss";
</style>
